package com.jdy.haoduoai.util;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;

import com.jdy.haoduoai.intface.IAsyncTask;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Executor;

/**
 * Modify to make it able to handle external UI controls.
 * 
 * @author zp @ 2015-5-21 上午9:47:32
 */

public class CustomAsyncTask extends AsyncTask<Void, Void, ResponseResult> {

  @SuppressWarnings("unused")
  private static final String TAG = "CustomAsyncTask";

  protected Activity mActivity;
  protected IAsyncTask mAsyncTask;
  private String mCustomAlterMessage = "请检查网络连接!";
  private Runnable mNoSuccessRunnable;

  public CustomAsyncTask(Activity activity, IAsyncTask iat) {
    mActivity = activity;
    mAsyncTask = iat;
  }

  private void setCustomAltertMessage(String msg) {
    mCustomAlterMessage = msg;
  }

  @Override
  protected ResponseResult doInBackground(Void... params) {
    if (mAsyncTask != null) {
      return mAsyncTask.doInbackground(mActivity);
    } else {
      return null;
    }
  }

  @Override
  protected void onPostExecute(ResponseResult result) {
    super.onPostExecute(result);
    if (result == null) {
      // Toast.makeText(mActivity, mCustomAlterMessage,
      // Toast.LENGTH_SHORT).show();
      if (mNoSuccessRunnable != null) {
        mNoSuccessRunnable.run();
      }

      if (mAsyncTask != null) {
        ResponseResult r = new ResponseResult(-1, "", -1);
        mAsyncTask.onRecieveData(mActivity, r);
      }
    } else {
      if (mAsyncTask != null) {
        mAsyncTask.onRecieveData(mActivity, result);
      }
    }
  }

  @Override
  protected void onCancelled() {
    super.onCancelled();

    if (mAsyncTask != null) {
      ResponseResult r = new ResponseResult(-1, "用户取消", -1);
      mAsyncTask.onRecieveData(mActivity, r);
    }
    mAsyncTask = null;
  }

  public void setSerialExecutor() {
    try {
      CustomAsyncTask.class.getMethod("setDefaultExecutor", Executor.class)
          .invoke(null, AsyncTask.SERIAL_EXECUTOR);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  }

  public void execute() {
    doExecute();
  }

  public void execute(String msg) {
    setCustomAltertMessage(msg);
    doExecute();
  }

  // public void execute(String msg, Runnable runnable) {
  // mNoSuccessRunnable = runnable;
  // setCustomAltertMessage(msg);
  // doExecute();
  // }

  private void doExecute() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      this.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
    } else {
      this.execute((Void[]) null);
    }
  }
}
